package com.example.carRental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.carRental.entity.LoginUser;
import com.example.carRental.entity.User;
import com.example.carRental.mapper.UserMapper;
import com.example.carRental.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author 92307
 * @version 1.0
 * @time 2022/3/20
 */

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService, UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user))throw new RuntimeException("用户名不存在");
        List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());
        return new LoginUser(user);
    }
}
